﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LibGreen.Protocol.IRC
{
	/// <summary>
	/// A command sent by the server to the client
	/// </summary>
	public class ServerMessage
	{
		private readonly static char[] spaceArray = { ' ' };
		#region ServerName
		private string serverName;

		public string ServerName
		{
			get { return serverName; }
			set { serverName = value; }
		} 
		#endregion
		#region SenderAlias
		private string senderAlias = null;

		public string SenderAlias
		{
			get 
			{
				if (string.IsNullOrEmpty(senderAlias))
					return SenderName;
				return senderAlias; 
			}
			set { senderAlias = value; }
		} 
		#endregion
		#region SenderName
		private string senderName = null;

		public string SenderName
		{
			get 
			{
				if (string.IsNullOrEmpty (senderName))
					return ServerName;
				return senderName; 
			}
			set { SenderName = value; }
		} 
		#endregion
		public string Command;
		public List<string> parameters = new List<string> ();
		public ServerMessage (byte[] packet)
		{
			string message = UTF8Encoding.UTF8.GetString (packet);
			message = parseHeader (message);
			var commandAndParameters = message.Split (spaceArray, 2);
			Command = commandAndParameters[0];
			if (commandAndParameters.Length == 2) {
				parseParameters (commandAndParameters[1]);
			}
			
		}

		private void parseParameters (string parametersList)
		{
			string[] spaceColonArray = new string[]{" :"};
			var restAndLast = parametersList.Split (spaceColonArray, 2, StringSplitOptions.RemoveEmptyEntries);
			parameters.AddRange(restAndLast[0].Split (spaceArray));
			if (restAndLast.Length == 2) {
				parameters.Add (restAndLast[1]);
			}
		}
		protected string parseHeader (string message)
		{
			if (message[0] == ':') {
				var messageArray = message.Split (spaceArray, 2);
				message = messageArray[1];
				var header = messageArray[0];
				header.Remove (0, 1);
				if (header.Contains ('@')) {
					var split = header.Split ('@');
					ServerName = split[1];
					header = split[0];
					if (header.Contains ('!')) {
						var split2 = header.Split ('!');
						SenderName = split2[1];
						header = split2[0];
					}
					senderAlias = header;
				}
				else
				ServerName = header;
			}
			return message;
		}
	}

}
